<template>
  <div class="input-module-box">
    <input
      type="text"
      :value="currentVal"
      @blur="inputHandle"
      @keyup.enter="inputHandle"
    />
    <button class="add" :disabled="currentVal === max" @click="carCountFn(1)">
      +
    </button>
    <button class="sub" :disabled="currentVal === min" @click="carCountFn(-1)">
      -
    </button>
  </div>
</template>

<script>
export default {
  name: 'inputModule',
  data() {
    return {
      currentVal: this.value,
    }
  },
  props: {
    value: { type: Number, required: true },
    min: { type: Number, default: 1 },
    max: { type: Number, default: 20 },
  },
  methods: {
    // 购物车数量加减
    carCountFn(num) {
      this.currentVal += num
    },
    inputHandle(e) {
      this.currentVal = e.target.value
    },
  },
  watch: {
    currentVal(nowVal, oldVal) {
      const { max, min } = this
      let newVal = Math.round(+nowVal)

      newVal = newVal < min ? min : newVal
      newVal = newVal > max ? max : newVal
      this.currentVal = newVal

      if (Number.isNaN(newVal)) {
        this.currentVal = oldVal
      }

      this.$emit('input', newVal)
    },
  },
}
</script>

<style lang="less" scoped>
.input-module-box {
  position: relative;
}
input {
  width: 40px;
  height: 40px;
  box-sizing: border-box;
  border: 1px solid #ddd;
  outline: none;
  line-height: 40px;
  text-align: center;
}
button {
  box-sizing: border-box;
  position: absolute;
  width: 20px;
  height: 20px;
  border: 1px solid #ddd;
  margin-left: -1px;
}
.add {
  top: 0;
}
.count button.sub {
  top: 19px;
  height: 21px;
}
</style>
